package com.peak.distribution.manager.agent.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.peak.distribution.entity.agent.DisAgent;
import com.peak.distribution.entity.agent.DisAgentTeam;
import com.peak.distribution.manager.agent.DisAgentTeamManager;
import com.peak.spring.boot.builder.repository.FilterParamBuilder;
import com.peak.spring.boot.core.manager.BaseManagerImpl;
import com.peak.spring.boot.tools.Converts;

@Component
@Transactional(readOnly = true)
public class DisAgentTeamManagerImpl extends BaseManagerImpl<DisAgentTeam> implements DisAgentTeamManager {

	@Override
	public DisAgentTeam getMyTeam(DisAgent leader) {
		return super.findOne("leader.id", leader.getId());
	}

	@Override
	public List<DisAgentTeam> getAllTeam(DisAgent leader) {
		List<DisAgent> allAgents = Lists.newArrayList(leader);
		DisAgent upAgent = leader.getParent();
		// 循环取上级代理
		while (upAgent != null && (upAgent = upAgent.getParent()) != null) {
			allAgents.add(upAgent);
		}
		// 获取所有的id
		String ids = allAgents.stream().map(p -> Converts.toString(p.getId())).collect(Collectors.joining(","));
		return super.findList(FilterParamBuilder.create().in("leader.id", ids).build());
	}

}
